package servlet;

import dao.CartDAO;
import entity.Cart;
import org.bson.types.ObjectId;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "cartCheckout", value = "/cart/checkout")
public class CartCheckOutServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userIdStr = req.getParameter("userId");
        String cartIdsStr = req.getParameter("cartIds");

        // 检查 userId 是否为空
        if (userIdStr == null || userIdStr.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "User ID is required");
            return;
        }

        // 检查 cartIds 是否为空
        if (cartIdsStr == null || cartIdsStr.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cart IDs are required");
            return;
        }

        // 验证 userId
        ObjectId userId;
        try {
            userId = new ObjectId(userIdStr);
        } catch (IllegalArgumentException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid User ID");
            return;
        }

        // 验证 cartIds
        String[] cartIdsArray = cartIdsStr.split(",");
        List<ObjectId> cartIds = new ArrayList<>();
        try {
            for (String idStr : cartIdsArray) {
                cartIds.add(new ObjectId(idStr));
            }
        } catch (IllegalArgumentException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Cart ID");
            return;
        }

        CartDAO cartDAO = new CartDAO();
        List<Cart> cartItems = cartDAO.findByIds(cartIds);

        // 检查是否找到有效的购物车项
        if (cartItems.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid cart items found");
            return;
        }

        double totalPrice = cartItems.stream().mapToDouble(item -> item.getPrice() * item.getNum()).sum();

        // 处理结算逻辑（例如减库存、生成订单等）
        // 这里假设结算成功，删除购物车项
        for (Cart cartItem : cartItems) {
            cartDAO.delCart(cartItem.getId());
        }

        req.setAttribute("totalPrice", totalPrice);
        resp.sendRedirect("/cart/userList");
    }
}